package com.techfort.affs;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.techfort.affs.mongoclient.MongolabClient;

public class Main extends Activity {
   
	
	AlertDialog  alert;
	
	MongolabClient client = new MongolabClient("affs", "users", "4ead9de7e4b0e737eda86573");
	EditText email;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        
        final StoredAccountAdapter db = new StoredAccountAdapter(getApplicationContext());
        db.open();
        // db.updateAccount("default");
        if(!db.getAccount().equals("default")){
        	startActivity(new Intent(Main.this, AffsTabs.class));
        }
        
        Button login = (Button) findViewById(R.id.login);
        
        email = (EditText) findViewById(R.id.email);
        
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("This email is not registered. Do you want to create an account?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					JSONObject newUser = new JSONObject();
					try {
						newUser.put("username", email.getText().toString());
						newUser.put("active", "yes");
						client.insert(newUser);
						db.updateAccount(email.getText().toString());
						dialog.cancel();
						if(db.getAccount().equals(email.getText().toString())){
							startActivity(new Intent(Main.this, AffsTabs.class));
						}
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
				}

			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					
				}
			});
		alert = builder.create();
        
        login.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				if(email.getText().equals("")){
					
				} else {
					List<NameValuePair> qparams = new ArrayList<NameValuePair>();
					qparams.add(new BasicNameValuePair("q", "{ \"username\" : \"" + email.getText() + "\"}"));
					JSONObject user = client.findOne(qparams);
					if(user==null){
						
						alert.show();
						
					} else {
						db.updateAccount(email.getText().toString());
						startActivity(new Intent(Main.this, AffsTabs.class));
					}		
				}
				
			}
		});
        
    }
    
}